package grammar;

import java.awt.Color;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.print.PrintException;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;

import DTO.Grammar;

import welcome.general.AboutTool;
import welcome.general.ChoosePerspective;
import facade.Facade;
import general.AspectLibraryException;
import general.NoPrinterInstalledFoundException;
import grammar.perspective.CanNotLoadGrammarOnScreenException;
import grammar.perspective.GrammarHasNotSyntaxAssociatedException;
import grammar.perspective.GrammarNotExistException;

public class GrammarEditingScreen {

	private static final String perspective = "Grammar Perspective";

	private static JFrame frmSetGrammar;
	private static GrammarEditingScreen window = null;

	private AboutTool aboutUs = null;

	private Facade facade = Facade.getInstance();
	private Grammar grammarFromBD;
	private Grammar grammarEditing = new Grammar("");

	private int countOfTextBaseAlteration =0, countUndo =0, countRedo =0;
	private List<String> baseOfAlterations = new ArrayList<String>();

	final JButton btnEdit = new JButton("Edit");

	public static JFrame getFrame() {
		return frmSetGrammar;
	}

	public static GrammarEditingScreen getWindow() {
		return window;
	}

	public GrammarEditingScreen() {
		aboutUs = new AboutTool();
		aboutUs.setVisible(false);

		btnEdit.setVisible(false);

		initialize();
	}

	private void closeFrame(){
		frmSetGrammar.setVisible(false);
	}

	private void back(){
		closeFrame();
		ChoosePerspective.getChooseAppScreen().setVisible(true);
	}

	/* Facade calling methods */
	private void saveGrammar(JButton btnSave, JMenuItem mntmSave, JTextArea tAreaScroll, JLabel lblSyntaxApproved){
		try {
			facade.setNewGrammar(new Grammar(tAreaScroll.getText()));
			btnSave.setEnabled(false);
			mntmSave.setEnabled(false);

			checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
			
			JOptionPane.showMessageDialog(null, "Grammar syntax sent for approbation.", "Successful Operation" ,JOptionPane.INFORMATION_MESSAGE);
			
			//TODO ir pra tela inicial 
			//TODO ir pra tela inicial
		} catch (GrammarHasNotSyntaxAssociatedException | GrammarNotExistException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), e.getExceptionTitle() ,JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e){
			JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_DB_ERROR, JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Checks if is necessary change the visible attribute of syntax approved label.
	 * 
	 * @param lblSyntaxApproved
	 * @param tAreaScroll
	 */
	private void checkVisibleOfSyntaxApprovedLabel(JLabel lblSyntaxApproved, JTextArea tAreaScroll){
		try {
			if(facade.getLastGrammar().getSyntax().equals(tAreaScroll.getText())){
				lblSyntaxApproved.setVisible(false);
			}else{
				lblSyntaxApproved.setVisible(true);
			}
		} catch (CanNotLoadGrammarOnScreenException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), e.getExceptionTitle() ,JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e){
			JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_DB_ERROR, JOptionPane.ERROR_MESSAGE);
		}
	}

	private Grammar retrivedGrammar() throws SQLException, CanNotLoadGrammarOnScreenException{
		return facade.getLastGrammar();
	}

	private void printGrammar(JTextArea tAreaScroll){
		try {
			facade.printText(tAreaScroll.getText());
		} catch (NoPrinterInstalledFoundException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), e.getExceptionTitle() ,JOptionPane.ERROR_MESSAGE);
		} catch (PrintException e){
			JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_ERROR, JOptionPane.ERROR_MESSAGE);
		}
	}

	/* GUI methods */
	private void changeEditableTextArea(JButton btnEdit, JTextArea tAreaScroll, JMenuItem mntmClear, JMenuItem mntmOrigGrammar, JMenuItem mntmUndo, JMenuItem mntmRedo){
		if(btnEdit.getText().equals("Edit")){
			btnEdit.setText("Not Edit");
			mntmClear.setEnabled(true);
			tAreaScroll.setEditable(true);
			checkEnableOfOriginalGrammarItem(mntmOrigGrammar);
			//Do not change the text, only set enable or not.
			getUndoText(tAreaScroll, true, mntmUndo);
			getRedoText(tAreaScroll, true, mntmRedo, false);
		}else{
			btnEdit.setText("Edit");
			tAreaScroll.setEditable(false);
			mntmClear.setEnabled(false);
			mntmOrigGrammar.setEnabled(false);
			mntmUndo.setEnabled(false);
			mntmRedo.setEnabled(false);
		}
	}

	private void showYesNoDialog(JButton btnSave, JMenuItem mntmSave, JTextArea tAreaScroll, JLabel lblSyntaxApproved){
		int userResponse = JOptionPane.showConfirmDialog(null ,"Save alterations?","Closing perspective...",JOptionPane.YES_NO_OPTION); 
		if (userResponse == JOptionPane.YES_OPTION) { 
			saveGrammar(btnSave, mntmSave, tAreaScroll, lblSyntaxApproved);
		}
	}

	private void checkBtnSaveAndTextAreaLength(JButton btnSave, JButton btnEdit, JMenuItem mntmSave, JTextArea tAreaScroll, JLabel lblLines){
		if(btnEdit.getText().equals("Not Edit")){
			btnSave.setEnabled(true);
			mntmSave.setEnabled(true);
		}

		lblLines.setText("Lines:  " + String.valueOf(tAreaScroll.getText().length()));
	}

	private void checkEnableOfOriginalGrammarItem(JMenuItem mntmOrigGrammar){
		if(!baseOfAlterations.isEmpty()){
			grammarEditing.setSyntax(baseOfAlterations.get(baseOfAlterations.size()-1));
			if(!grammarEditing.getSyntax().equals(grammarFromBD.getSyntax())){
				mntmOrigGrammar.setEnabled(true);
			}else{
				mntmOrigGrammar.setEnabled(false);
			}
		}
	}

	/* Redo and undo methods. */
	/**
	 * Fill the baseOfAlteration array with syntax text.
	 * 
	 * @param tAreaScroll
	 * @param mntmUndo
	 * @param mntmRedo
	 * @param mntmOrigGrammar
	 * @param lblSyntaxApproved
	 */
	private void addTextWritedOnBaseOfAlterations(JTextArea tAreaScroll, JMenuItem mntmUndo, JMenuItem mntmRedo, JMenuItem mntmOrigGrammar, JLabel lblSyntaxApproved){
		boolean isBaseEmpty = baseOfAlterations.isEmpty();
		if(isBaseEmpty || !baseOfAlterations.get(countOfTextBaseAlteration-1).equals(tAreaScroll.getText())){
			baseOfAlterations.add(tAreaScroll.getText());
			countOfTextBaseAlteration++;
			countRedo=0; countUndo=0;

			//Do not change the text, only set enable or not.
			getUndoText(tAreaScroll, true, mntmUndo);
			getRedoText(tAreaScroll, true, mntmRedo, false);

			if(baseOfAlterations.size() == 1)
				mntmUndo.setEnabled(true);
		}

		checkEnableOfOriginalGrammarItem(mntmOrigGrammar);
		checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);

	}

	private String getUndoText(JTextArea tAreaScroll, boolean updateValue, JMenuItem mntmUndo){
		int positionToGetText = countOfTextBaseAlteration + countRedo - (countUndo+2);
		boolean expressionToGetText = positionToGetText >=0;

		if(expressionToGetText){
			if(updateValue)
				countUndo++;
			setEnableOnMenuItem(mntmUndo, positionToGetText, 0, false);

			return baseOfAlterations.get(positionToGetText);
		}
		return tAreaScroll.getText();
	}

	private String getRedoText(JTextArea tAreaScroll, boolean updateValue, JMenuItem mntmRedo, boolean isActionListenner){
		int positionToGetText = countOfTextBaseAlteration - countUndo + (countRedo);
		boolean expressionToGetText = positionToGetText < baseOfAlterations.size();

		if(expressionToGetText){
			if(updateValue)
				countRedo++;
			setEnableOnMenuItem(mntmRedo, positionToGetText, baseOfAlterations.size()-1, isActionListenner);

			return baseOfAlterations.get(positionToGetText);
		}
		return tAreaScroll.getText();
	}

	private void setEnableOnMenuItem(JMenuItem item, int position, int value, boolean isRedoButtonActionListenner){
		if(btnEdit.getText().equals("Not Edit")){
			if(!isRedoButtonActionListenner && position == value){
				item.setEnabled(false);
			}else if(!isRedoButtonActionListenner && position == value || /* Is to only validate Redo (no getText)*/ isRedoButtonActionListenner && position != value){
				item.setEnabled(true);
			}else
				item.setEnabled(true);
		}
	}

	private void initialize() {
		/* Frame settings */
		frmSetGrammar = new JFrame();
		frmSetGrammar.getContentPane().setBackground(new Color(245, 245, 245));
		frmSetGrammar.setBounds(100, 100, 780, 600);
		frmSetGrammar.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\logo\\logo3.png"));
		frmSetGrammar.setTitle(ChoosePerspective.NAME_APP + " " + ChoosePerspective.VERSION  + " - " + perspective);
		frmSetGrammar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmSetGrammar.setLocation(
				((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (frmSetGrammar
						.getWidth() / 2)), ((Toolkit.getDefaultToolkit()
								.getScreenSize().height / 2) - (frmSetGrammar.getHeight() / 2)));

		JSeparator separator = new JSeparator();
		separator.setForeground(Color.GRAY);

		/* Edit button. */
		btnEdit.setVisible(true);
		btnEdit.setFocusable(false);
		btnEdit.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\edit_gray.png"));
		btnEdit.setBackground(SystemColor.controlHighlight);

		/* Back button. */
		JButton bntBack = new JButton("< back");
		bntBack.setBackground(SystemColor.controlHighlight);

		/* Scroll pane. */
		JScrollPane scrGrammar = new JScrollPane();
		scrGrammar.setToolTipText("");
		scrGrammar.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrGrammar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

		/* Save button. */
		final JButton btnSave = new JButton("save");
		btnSave.setEnabled(false);
		btnSave.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\save.png"));
		btnSave.setBackground(SystemColor.controlHighlight);

		/* Label step. */
		JLabel lblOf = new JLabel("Step 1 of 1");
		lblOf.setFont(new Font("Times New Roman", Font.PLAIN, 12));

		/* Text are component. */
		final JTextArea tAreaScroll = new JTextArea("");
		tAreaScroll.setColumns(10);
		tAreaScroll.setRows(15);
		tAreaScroll.setEditable(false);
		String dateModified = null;
		try {
			if(aboutUs != null){
				grammarFromBD = retrivedGrammar();
				dateModified = grammarFromBD.getTimeStamp().toString();
				tAreaScroll.setText(grammarFromBD.getSyntax());
			}
		} catch (CanNotLoadGrammarOnScreenException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), e.getExceptionTitle() ,JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e){
			JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_DB_ERROR, JOptionPane.ERROR_MESSAGE);
		}

		/* Lines count label. */
		final JLabel lblLines = new JLabel("Lines: ");
		lblLines.setFont(new Font("Times New Roman", Font.PLAIN, 12));
		lblLines.setText("Lines:  " + String.valueOf(tAreaScroll.getText().length()));

		/* Label last modified. */
		JLabel lblLastModified = new JLabel("Last Modification: 00:00:00 0000/00/00");
		if(dateModified!=null){
			String date = dateModified.split(" ")[0];
			String time = dateModified.split(" ")[1];
			lblLastModified.setText("Last Modification: " + time.substring(0,8) + " " + date.split("-")[2] + "/" + date.split("-")[1] + "/" + date.split("-")[0]);
		}
		lblLastModified.setFont(new Font("Times New Roman", Font.PLAIN, 12));

		/* Grammar not approved yet label. */
		final JLabel lblSyntaxApproved = new JLabel("This grammar syntax is not approved yet.");
		lblSyntaxApproved.setFont(new Font("Times New Roman", Font.PLAIN, 12));
		lblSyntaxApproved.setForeground(new Color(255, 0, 0));
		checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);

		/* Menu bar */
		JMenuBar menuBar = new JMenuBar();
		frmSetGrammar.setJMenuBar(menuBar);

		/* Menu - File: */
		JMenu mnFile = new JMenu("File");
		mnFile.setMnemonic('f');
		mnFile.setBackground(UIManager.getColor("CheckBox.highlight"));
		menuBar.add(mnFile);

		/* Clear menu item. */
		final JMenuItem mntmClear = new JMenuItem("Clear");
		mntmClear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
		mntmClear.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\clear_gray.png"));
		mnFile.add(mntmClear);
		mntmClear.setEnabled(false);

		/* Save menu item. */
		final JMenuItem mntmSave = new JMenuItem("Save");
		mntmSave.setEnabled(false);
		mntmSave.setBackground(SystemColor.control);
		mntmSave.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\save.png"));
		mnFile.add(mntmSave);

		/* Refresh menu item and separator. */
		JSeparator separator_2 = new JSeparator();
		mnFile.add(separator_2);
		JMenuItem mntmRefresh = new JMenuItem("Refresh");
		mntmRefresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
		mntmRefresh.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\refresh_2.png"));
		mnFile.add(mntmRefresh);

		/* Export menu item and separator */
		JSeparator separator_3 = new JSeparator();
		mnFile.add(separator_3);
		JMenuItem mntmExport = new JMenuItem("Export..");
		mntmExport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));
		mntmExport.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\export_gray.png"));
		mnFile.add(mntmExport);

		/* Print menu item. */
		JMenuItem mntmPrint = new JMenuItem("Print");
		mntmPrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
		mntmPrint.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\print_gray.png"));
		mnFile.add(mntmPrint);

		/* Separator */
		JSeparator separator_1 = new JSeparator();
		mnFile.add(separator_1);

		/* Exit menu item. */
		JMenuItem mntmExit = new JMenuItem("Quit");
		mntmExit.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\exit_white.png"));
		mntmExit.setBackground(SystemColor.control);
		mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
		mnFile.add(mntmExit);

		/* Menu - Edit: */
		JMenu mnEdit = new JMenu("Edit");
		mnEdit.setMnemonic('e');
		menuBar.add(mnEdit);

		/* Original grammar menu item. */
		final JMenuItem mntmOriginalGrammar = new JMenuItem("Original Grammar");
		mntmOriginalGrammar.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
		mntmOriginalGrammar.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\original_grammar_gray.png"));
		mnEdit.add(mntmOriginalGrammar);
		mntmOriginalGrammar.setEnabled(false);

		/* Undo menu item. */
		final JMenuItem mntmUndoTyping = new JMenuItem("Undo Typing");
		mntmUndoTyping.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\undo_gray.png"));
		mnEdit.add(mntmUndoTyping);
		mntmUndoTyping.setEnabled(false);

		/* Redo menu item. */
		final JMenuItem mntmRedo = new JMenuItem("Redo");
		mntmRedo.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\redo_gray.png"));
		mnEdit.add(mntmRedo);
		mntmRedo.setEnabled(false);

		/* Menu - Help: */
		JMenu mnHelp = new JMenu("Help");
		mnHelp.setMnemonic('h');
		menuBar.add(mnHelp);

		/* About menu item. */
		JMenuItem mntmAbout_1 = new JMenuItem("About");
		mntmAbout_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
		mnHelp.add(mntmAbout_1);
		mntmAbout_1.setBackground(SystemColor.control);
		mntmAbout_1.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\about_gray.png"));


		/* -------------------- Events -------------------- */

		/* About button event. */
		mntmAbout_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				aboutUs.setVisible(true);	
			}
		});

		/* Redo and undo buttons event. */
		mntmRedo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tAreaScroll.setText(getRedoText(tAreaScroll, true, mntmRedo, false));	
				//Do not change the text, only set enable or not.
				getUndoText(tAreaScroll, false, mntmUndoTyping);
				checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
			}
		});
		mntmUndoTyping.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tAreaScroll.setText(getUndoText(tAreaScroll, true, mntmUndoTyping));
				//Do not change the text, only set enable or not.
				getRedoText(tAreaScroll, false,  mntmRedo, true);
				checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
			}
		});

		/* Exit buttons event. */
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(btnSave.isEnabled() || mntmSave.isEnabled()){
					showYesNoDialog(btnSave, mntmSave, tAreaScroll, lblSyntaxApproved);
				}
				System.exit(0);
			}
		});

		/* Edit buttons event. */
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				changeEditableTextArea(btnEdit, tAreaScroll, mntmClear, mntmOriginalGrammar, mntmUndoTyping, mntmRedo);
			}
		});

		/* Keyboard event on text area. */
		tAreaScroll.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				checkBtnSaveAndTextAreaLength(btnSave, btnEdit, mntmSave, tAreaScroll, lblLines);
				addTextWritedOnBaseOfAlterations(tAreaScroll, mntmUndoTyping, mntmRedo, mntmOriginalGrammar, lblSyntaxApproved);
			}
			@Override
			public void keyReleased(KeyEvent arg0) {
				checkBtnSaveAndTextAreaLength(btnSave, btnEdit, mntmSave, tAreaScroll, lblLines);
				addTextWritedOnBaseOfAlterations(tAreaScroll, mntmUndoTyping, mntmRedo, mntmOriginalGrammar, lblSyntaxApproved);
			}
			@Override
			public void keyTyped(KeyEvent e) {
				checkBtnSaveAndTextAreaLength(btnSave, btnEdit, mntmSave, tAreaScroll, lblLines);
				addTextWritedOnBaseOfAlterations(tAreaScroll, mntmUndoTyping, mntmRedo, mntmOriginalGrammar, lblSyntaxApproved);
			}
		});

		/* Back button event. */
		bntBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(btnSave.isEnabled() || mntmSave.isEnabled()){
					showYesNoDialog(btnSave, mntmSave, tAreaScroll, lblSyntaxApproved);
				}
				back();
			}
		});

		/* Save buttons event. */
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveGrammar(btnSave, mntmSave, tAreaScroll, lblSyntaxApproved);
			}
		});
		mntmSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveGrammar(btnSave, mntmSave, tAreaScroll, lblSyntaxApproved);
			}
		});

		/* Original grammar event. */
		mntmOriginalGrammar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				grammarEditing.setSyntax(grammarFromBD.getSyntax());	
				tAreaScroll.setText(grammarEditing.getSyntax());
				checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
				mntmOriginalGrammar.setEnabled(false);
			}
		});

		/* Clear event */
		mntmClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				grammarEditing.setSyntax("");
				tAreaScroll.setText(grammarEditing.getSyntax());
				mntmSave.setEnabled(true);
				btnSave.setEnabled(true);
				checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
			}
		});

		/* Refresh event */
		mntmRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkVisibleOfSyntaxApprovedLabel(lblSyntaxApproved, tAreaScroll);
			}
		});

		/* Print event */
		mntmPrint.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				printGrammar(tAreaScroll);
				//JOptionPane.showMessageDialog(null, "Printing done.", "Successful Operation" ,JOptionPane.INFORMATION_MESSAGE);
			}
		});

		/* Export event */
		mntmExport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser("C:\\Users\\F. OMENA\\Desktop");  
				fileChooser.setBackground(new Color(245, 245, 245));
				fileChooser.setDialogTitle("Save grammar syntax");
				//To set image icon
				int returnVal = fileChooser.showSaveDialog(frmSetGrammar); 

				File dirToSave = fileChooser.getSelectedFile();
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					try {
						FileWriter fileWriter = new FileWriter(dirToSave+".txt");
						BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
						PrintWriter printWriter = new PrintWriter(bufferedWriter);
						printWriter.println(tAreaScroll.getText());
						printWriter.flush();
						printWriter.close();

						JOptionPane.showMessageDialog(null, "The file is available on: " + dirToSave+".txt" + ".", "Successful Operation" ,JOptionPane.INFORMATION_MESSAGE);
					} catch (IOException e1){
						JOptionPane.showMessageDialog(null, e1.getStackTrace(), e1.getMessage(), JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});

		/* Layout */
		GroupLayout groupLayout = new GroupLayout(frmSetGrammar.getContentPane());
		groupLayout.setHorizontalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
						.addGap(10)
						.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.RELATED)
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(scrGrammar, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE)
								.addGroup(groupLayout.createSequentialGroup()
										.addComponent(btnEdit)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(lblSyntaxApproved)
										.addPreferredGap(ComponentPlacement.RELATED, 414, Short.MAX_VALUE)
										.addComponent(lblOf))
										.addGroup(groupLayout.createSequentialGroup()
												.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
														.addComponent(lblLines)
														.addComponent(bntBack))
														.addPreferredGap(ComponentPlacement.RELATED, 479, Short.MAX_VALUE)
														.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
																.addComponent(btnSave)
																.addComponent(lblLastModified))))
																.addContainerGap())
				);
		groupLayout.setVerticalGroup(
				groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
						.addGap(14)
						.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
										.addComponent(btnEdit)
										.addComponent(lblOf)
										.addComponent(lblSyntaxApproved))
										.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
										.addGap(15)
										.addComponent(scrGrammar, GroupLayout.PREFERRED_SIZE, 418, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
												.addComponent(lblLines)
												.addComponent(lblLastModified))
												.addPreferredGap(ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
												.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
														.addComponent(bntBack)
														.addComponent(btnSave))
														.addContainerGap())
				);
		scrGrammar.setViewportView(tAreaScroll);
		frmSetGrammar.getContentPane().setLayout(groupLayout);
	}
}
